package com.ylsk.common.utils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * FileName BeanUtils
 * Description Bean工具类
 * author Administrator
 * version V1.0
 */
public class BeanUtils {


    private BeanUtils(){

    }

    public static Map<String,Object> bean2Map(Object obj)
            throws IntrospectionException, InvocationTargetException, IllegalAccessException{
        if (obj == null) {
            return null;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            // 过滤class属性
            if (!key.equals("class")) {
                // 得到property对应的getter方法
                Method getter = property.getReadMethod();
                Object value = getter.invoke(obj);
                if(value !=null){
                    map.put(key, value);
                }
            }
        }
        return map;
    }
}
